'use client';

import { useToast } from '@/hooks/use-toast';
import { genQualificationImageKey } from '@/lib/cos';
import { result } from '@/lib/utils';
import { useCosClient } from '@/providers/cos-provider';
import {
  shopUpdateShopStatus,
  updateShopQualification,
} from '@/service/actions/shop';
import type { ShopType } from '@/service/type/shop';
import { useState, useTransition } from 'react';
import ImageUploader from '../common/image-uploader';
import QueryImage from '../common/query-image';
import { Button } from '../ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '../ui/dialog';
import ImagePopover from './image-popover';

export default function UploadQualification({
  shopData,
}: { shopData: ShopType }) {
  const [open, setOpen] = useState(false);
  const { toast } = useToast();
  const cosClient = useCosClient();
  const [isPending, startTransition] = useTransition();

  const onUploaded = async ({
    newLicenseKey,
    newHygieneCertKey,
  }: {
    newLicenseKey?: string | null;
    newHygieneCertKey?: string | null;
  }) => {
    const { error } = await updateShopQualification({
      licenseKey: newLicenseKey ?? shopData.licenseKey,
      hygieneCertKey: newHygieneCertKey ?? shopData.hygieneCertKey,
    });
    error
      ? toast({
          title: error.message,
          variant: 'destructive',
        })
      : toast({
          title: '上传成功',
        });
  };

  const onDelete = async (type: 'license' | 'hygieneCert') => {
    if (!cosClient) return result();
    if (type === 'license') {
      const { error } = await updateShopQualification({
        hygieneCertKey: shopData.hygieneCertKey,
        licenseKey: null,
      });
      !error && shopData.licenseKey && cosClient.delete([shopData.licenseKey]);
      !error &&
        toast({
          title: '删除成功',
        });
      return error ? result(error, error.message) : result();
    }
    const { error } = await updateShopQualification({
      hygieneCertKey: null,
      licenseKey: shopData.licenseKey,
    });
    !error &&
      shopData.hygieneCertKey &&
      cosClient.delete([shopData.hygieneCertKey]);
    !error &&
      toast({
        title: '删除成功',
      });
    return error ? result(error, error.message) : result();
  };

  return (
    <Dialog open={open}>
      <DialogTrigger asChild onClick={() => setOpen(true)}>
        <Button
          disabled={
            shopData.status !== 'unreviewed' && shopData.status !== 'rejected'
          }
        >
          上传资质
        </Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>上传资质</DialogTitle>
          <DialogDescription>上传资质</DialogDescription>
        </DialogHeader>
        <div className="flex gap-5 items-center justify-center">
          <div className="w-full h-32 flex items-center justify-center">
            {shopData.licenseKey ? (
              <ImagePopover
                imageKey={shopData.licenseKey}
                onDelete={() => onDelete('license')}
              >
                <QueryImage
                  imageKey={shopData.licenseKey}
                  wrapperClassName="w-full h-32"
                  imgClassName="w-full h-full object-cover"
                />
              </ImagePopover>
            ) : (
              <ImageUploader
                button={<Button>上传营业执照</Button>}
                genImageKey={() => genQualificationImageKey(shopData.userId)}
                onUploaded={(keys) => onUploaded({ newLicenseKey: keys[0] })}
                single
              />
            )}
          </div>
          <div className="w-full h-32 flex items-center justify-center">
            {shopData.hygieneCertKey ? (
              <ImagePopover
                imageKey={shopData.hygieneCertKey}
                onDelete={() => onDelete('hygieneCert')}
              >
                <QueryImage
                  imageKey={shopData.hygieneCertKey}
                  wrapperClassName="w-full h-32"
                  imgClassName="w-full h-full object-cover"
                />
              </ImagePopover>
            ) : (
              <ImageUploader
                button={<Button>上传卫生许可证</Button>}
                genImageKey={() => genQualificationImageKey(shopData.userId)}
                onUploaded={(keys) =>
                  onUploaded({ newHygieneCertKey: keys[0] })
                }
                single
              />
            )}
          </div>
        </div>
        <DialogFooter className="gap-3 pt-3">
          <Button variant="outline" onClick={() => setOpen(false)}>
            关闭
          </Button>
          <Button
            disabled={
              isPending ||
              !shopData.licenseKey ||
              !shopData.hygieneCertKey ||
              (shopData.status !== 'unreviewed' &&
                shopData.status !== 'rejected')
            }
            onClick={() =>
              startTransition(async () => {
                const { error } = await shopUpdateShopStatus('reviewing');
                error
                  ? toast({ title: error.message, variant: 'destructive' })
                  : toast({ title: '提交审核成功' });
              })
            }
          >
            {isPending && <span className="i-ri-loader-4-line animate-spin" />}
            提交审核
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
